package org.chat.hhdchat.config;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import org.chat.hhdchat.handler.ChatServerHandler;
import org.chat.hhdchat.handler.ChatServerInitializer;
import org.chat.hhdchat.repository.ChatMessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 核心业务前置
 */
// Netty服务器启动类
@Component // 标注该类为 Spring 管理的 Bean，方便依赖注入
public class NettyServer {
    private final int port = 8081;
    private final ChatServerHandler chatServerHandler;

    @Autowired
    public NettyServer(ChatServerHandler chatServerHandler) {
        this.chatServerHandler = chatServerHandler;
    }

    public void start() {
        System.out.println("start netty server...");
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            // HTTP 编解码器（WebSocket 基于 HTTP）
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new HttpObjectAggregator(65536));
                            // WebSocket 协议处理器（路径 /ws）
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
                            // 自定义消息处理器
                            pipeline.addLast(chatServerHandler);
                        }
                    });
            ChannelFuture future = bootstrap.bind(port).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
    /**
     *private final int port = 8081; // 服务端监听的端口
     *
     *     @Autowired // Spring 会自动注入 ChatMessageRepository 实例
     *     private ChatMessageRepository chatMessageRepository;
     *
     *     public void start() {
     *         // 创建 Boss 线程组，用于接收客户端连接
     *         EventLoopGroup bossGroup = new NioEventLoopGroup();
     *         // 创建 Worker 线程组，用于处理与客户端的网络 I/O 操作
     *         EventLoopGroup workerGroup = new NioEventLoopGroup();
     *
     *         try {
     *             // 创建 ServerBootstrap 对象，设置服务器的各项配置
     *             ServerBootstrap bootstrap = new ServerBootstrap();
     *             bootstrap.group(bossGroup, workerGroup) // 设置 Boss 和 Worker 线程组
     *                     .channel(NioServerSocketChannel.class) // 设置服务器通道类型，NIO 通道
     *                     .childHandler(new ChatServerInitializer(chatMessageRepository)); // 配置处理 I/O 事件的处理器
     *
     *             // 绑定端口并启动服务器
     *             ChannelFuture future = bootstrap.bind(port).sync(); // 绑定端口并同步等待完成
     *
     *             // 等待服务端关闭
     *             future.channel().closeFuture().sync(); // 阻塞，直到服务端通道关闭
     *         } catch (InterruptedException e) {
     *             e.printStackTrace(); // 异常处理
     *         } finally {
     *             // 关闭线程池
     *             bossGroup.shutdownGracefully(); // 优雅地关闭 Boss 线程组
     *             workerGroup.shutdownGracefully(); // 优雅地关闭 Worker 线程组
     *         }
     *     }
     *
     */

}